/*global Ext, Portal */
var glob;

Ext.Window.prototype.floating = { shadow: false };
Ext.apply(Portal, {
	oCenterRegion: null,
	oNorthRegion: null
});

//se creaza namespace-ul main
Ext.ns('Portal.main');
Ext.apply(Portal.main, {
	//functie de schimabre parola
	changePass: function () {
		Ext.MessageBox.prompt('Schimbare Parola', 'Parola :',
			function (btn, text) {
				if (btn == 'ok') {
					Ext.Ajax.request({
						url: 'user/addPass/' + Math.random(),
						params: {
							pass: text
						}
					});
				}
			});
	}
});

Ext.ns('Portal.events');


//creare seturi functii mesaje
Ext.apply(Portal.events, {
	/**
	 * Usage: Portal.events.throwError('Error description here!');
	 * @param {String} msg
	 */
	throwError: function (msg) {
		Ext.ux.PortalToast.msg({
			title: 'Eroare',
			iconCls: 'icon-fugue-slash'
		}, '{0}', msg);
	},

	throwInformation: function (msg) {
		Ext.ux.PortalToast.msg({
			title: 'Informatie',
			iconCls: 'icon-fugue-information'
		}, '{0}', msg);
	},
	throwWarning: function (msg) {
		Ext.ux.PortalToast.msg({
			title: 'Avertisment',
			iconCls: 'icon-fugue-exclamation'
		}, '{0}', msg);
	}
});

//creare seturi functii de suprascriu functiile AJAX a.i. daca sa se afiseze mesaje ( confirmari , erori) pe interfata utilizatorului )
Ext.apply(Portal.events, {

	beforeRequest: function (conn, response, options) {
		//console.log("inainte de request");
		Ext.getCmp("logmessages").el.mask("Loading..");
	},

	requestException: function (conn, response, options) {
		Ext.getCmp("logmessages").el.unmask();
		//console.log("problema");
		Portal.events.parseJsonResponse(conn, response, options, true);
	},

	requestComplete: function (conn, response, options) {
		//console.log("request terminat");
		Ext.getCmp("logmessages").el.unmask();
		Portal.events.parseJsonResponse(conn, response, options);
	},

	parseJsonResponse: function (conn, response, options, exception) {
		// case there is an exception throw an error
		try {
			if (exception !== undefined) {
				//console.log(response);
				Portal.events.throwError('[status: ' + response.status + '] ' + response.statusText);
				//return;
			}
		}
		catch (e) {
		}

		try {
			// daca raspunsul este json clasic
			if ((   response.responseText.search(/\{"error":/i) !== -1    ) || (    response.responseText.search(/\{'error':/i) !== -1  )) {
				//console.info('DO DECODE');
				var oResponse = Ext.decode(response.responseText);

				if (oResponse.error !== undefined) {
					if (( oResponse.error === true  ) || ( oResponse.error == 'true'  )) {
						Portal.events.throwError('[' + oResponse.type + '] ' + oResponse.description);
						if (oResponse.type == 'nosession') {
							//Ext.MessageBox.alert('Status', 'Sesiunea a expirat.. ');
						}
						return;
					}
					else if ((oResponse.error === false  ) || (oResponse.error == 'false')) {

						if (oResponse.type != 'silent') { // silent response, do not echo
							if (oResponse.description) {
								Portal.events.throwInformation(oResponse.description);
							}
							return;
						}
					}
				}
			}
		}
		catch (er) {
			//console.error(e);
		}

	}
});

// adaugare functii pentru preluare mesaje ajax
Ext.Ajax.on('beforerequest', Portal.events.beforeRequest, this);
Ext.Ajax.on('requestcomplete', Portal.events.requestComplete, this);
Ext.Ajax.on('requestexception', Portal.events.requestException, this);

Ext.apply(Portal.main, {
	exec: function () {
		var oNorthRegion = {
			region: 'north',
			html: '<div></div>',
			tbar: [
				{
					xtype: 'buttongroup',
					columns: 4,
					items: [
						{
							xtype: 'tbbutton',
							text: 'Setari',
							iconCls: 'icon-fugue-globe',
							menu: [
								{
									text: 'Schimbare parola',
									iconCls: 'icon-fugue-key',
									handler: Portal.main.changePass
								},
								/*{
									iconCls: 'icon-fugue-smiley-cool',
									text: 'Semnatura',
									//handler: Portal.signScreen.exec
								}*/
							]
						},
						{
							xtype: "tbbutton",
							iconCls: 'icon-group',
							text: 'Baza Date',
							handler: Portal.baza.exec
						},/*
						{
							xtype: "tbbutton",
							iconCls: 'icon-cog',
							text: 'Campanii',
							//handler: Portal.main.fnOpenCampaignScreen
						},
						{
							text: 'Telemarketing',
							iconCls: 'icon-telephone',
							menu: new Ext.menu.Menu({
								items: [
									{
										iconCls: 'icon-newspaper',
										text: 'Status',
										//handler: Portal.teleStatusScreen.exec
									},
									{
										iconCls: 'icon-fugue-question-frame',
										text: 'Intrebari',
										//handler: Portal.teleQuestionScreen.exec
									},
									{
										iconCls: 'icon-fugue-question-frame',
										text: 'Intrebari cu raspuns liber',
										//handler: Portal.teleQuestionFreeScreen.exec
									},
									{
										iconCls: 'icon-fugue-question-frame',
										text: 'Campuri custom',
										//handler: Portal.teleCustomScreen.exec
									},
									{
										iconCls: 'icon-telephone',
										text: 'Telemarketing',
										//handler: Portal.teleScreen.exec
									}
								]
							})
						},*/
						{
							text: 'Operatii',
							iconCls: 'icon-fugue-printer',
							menu: new Ext.menu.Menu({
								id: 'menuObjects',
								style: {
									overflow: 'visible'
								}
							})
						},/*
						{
							text: 'Rapoarte',
							iconCls: 'icon-fugue-chart',
							menu: new Ext.menu.Menu({
								items: [
									{
										iconCls: 'icon-fugue-chart',
										text: 'Chart Useri',
										//handler: Portal.main.fnOpenRaport1Screen
									},
									{
										iconCls: 'icon-fugue-chart',
										text: 'Chart General',
										//handler: Portal.main.fnOpenRaport2Screen
									},
									{
										iconCls: 'icon-user-gray',
										text: 'Nr. contacte lucrate / zi',
										handler: function () {
											window.location.href = 'raport/dayContact/';
										}
									},
									{
										text: 'Telemarketing',
										iconCls: 'icon-fugue-table-excel',
										//handler: Portal.report.getTelemarketing
									},
									{
										text: 'Link-uri Campanii',
										iconCls: 'icon-fugue-table-excel',
										//handler: Portal.report.getCampanieLinkuri
									}
								]
							})
						},
						{
							text: 'Mailer',
							iconCls: 'icon-fugue-mail-open-image',
							menu: new Ext.menu.Menu({
								items: [
									{
										text: 'Setari Mailer',
										iconCls: 'icon-clock-edit',
										//handler: Portal.main.fnOpenMailerScreen
									},
									{
										text: 'Programari Mailer',
										iconCls: 'icon-clock-play',
										//handler: Portal.main.fnOpenMailerTaskScreen
									}
								]
							})
						}*/
					]
				},
				{
					xtype: "buttongroup",
					columns: 2,
					hidden: (Portal.user_rol == 'user' ),
					items: [
						{
							xtype: 'tbbutton',
							iconCls: 'icon-fugue-wrench-screwdriver',
							text: 'Corector',
							menu: new Ext.menu.Menu({
								items: [
									{
										text: 'Client - Campanii',
										handler: Portal.corectorClientCampanie.exec
									} /* ,
									 {
									 iconCls: 'icon-vcard',
									 text: 'Logo MTP',
									 //handler: Portal.logoScreen.exec
									 }*/
								]
							})
							//handler: Portal.main.fnOpenCorrectorScreen
						},
						{
							text: 'Administrare',
							xtype: 'tbbutton',
							iconCls: 'icon-fugue-user-black',
							menu: new Ext.menu.Menu({
								//style: {overflow: 'visible' },
								items: [
									{
										iconCls: 'icon-fugue-users',
										text: 'Useri',
										handler: Portal.user.exec
									} /* ,
									 {
									 iconCls: 'icon-vcard',
									 text: 'Logo MTP',
									 //handler: Portal.logoScreen.exec
									 }*/
								]
							})
						},
						{
							iconCls: 'icon-fugue-smiley-twist',
							text: 'Import',
							//handler: Portal.main.fnOpenImportScreen
						} ,
						{
							xtype: 'tbbutton',
							iconCls: 'icon-fugue-information-shield',
							text: 'Suport',
							handler: Portal.suport.exec
						}
					]
				},
				{
					xtype: "panel",
					width: 450,
					height: 40,
					id: "logmessages",
					cls: "logmessages",
					frame: true,
					autoScroll: true,
					autoHeight: true
				},
				'->',
				{
					text: 'Logout',
					iconCls: 'icon-fugue-control-power',
					handler: function () {
						window.location = 'main/do_logout';
					}
				}
			]
		};

		var oCenterRegion = {
			region: 'center',
			xtype: 'tabpanel',
			activeItem: 0,
			//enableTabScroll: true,
			resizeTabs: true,
			minTabWidth: 100,
			hideMode: "offsets",
			deferredRender: false,
			defaults: {
				closable: true
			},
			items: [
				/*{
				 html: "User Raport ..work in progress",
				 title: "Welcome",
				 hidden : true
				 }*/
			],
			//se pune conditie la stergerea unui tab si anume la inchiderea unui tab de contact
			//daca se deschide un tab de contact dar nu se salveaza , la inchidere tab apare o fereastra de confirmare
			// in fiecare contact se pune un obiect cu id "fpContact_saved_"+id in care se seteaza daca contactul a fost sau nu salvat vezi contact.js
			listeners: {
				"beforeremove": function (container, component) {

					var idComp = component.id;
					id = idComp.substr(8, id.length);

					if (component.findById("fpContact_saved_" + id)) {
						var saved = component.findById("fpContact_saved_" + id).getValue();
						if (saved == "0") {
							if (container.removeConfirmed) {
								delete container.removeConfirmed;
								return true;
							}
							Ext.Msg.confirm('Confirmare', 'Sigur doriti sa inchideti ?',
								function (btn) {
									if (btn == 'yes') {
										container.removeConfirmed = true;
										container.remove(component);
									}
								});
							return false;
						}
						/*if (saved == "1") {
						 return true;
						 }*/
					}
					return true;
				}
			}
		};

		var oAppViewport = new Ext.Viewport({
			layout: 'border',
			items: [oNorthRegion, oCenterRegion],
			renderTo: Ext.getBody()
		});

		Portal.oNorthRegion = oAppViewport.getComponent(0);
		Portal.oCenterRegion = oAppViewport.getComponent(1);
	}
});
